package com.share.example.sbsjw.algorithm;

import com.google.common.collect.Range;
import com.share.common.utils.DateExtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.Collection;
import java.util.Date;
import java.util.HashSet;

//范围的分片算法类名称，用于BETWEEN
@Slf4j
public class DateTimeBetweenAlgorithm implements RangeShardingAlgorithm<Date> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {
        int colSize = collection.size();
        String[] array = collection.toArray(new String[colSize]);

        Range<Date> valueRange = rangeShardingValue.getValueRange();
        String logicTableName = rangeShardingValue.getLogicTableName();
        Date min = valueRange.hasLowerBound() ? valueRange.lowerEndpoint() : dealTableName(array[0]);//查询下限值
        Date max = valueRange.hasUpperBound() ? valueRange.lowerEndpoint() : dealTableName(array[colSize - 1]);//查询上限值

        Date tmpDate = min;
        final Collection<String> tableSet = new HashSet();
        while (DateExtUtil.compareYearMonth(tmpDate, max) < 1) {
            String realtable =AllTableConfig.getPhysicsTableName(logicTableName,tmpDate);
            if (collection.contains(realtable)) {//将当前取值对应的数据库节点存入返回set中
                tableSet.add(realtable);
            }

            //包含了所以直接跳过
            if (colSize == tableSet.size()) {
                break;
            }

            tmpDate = DateExtUtil.addMonth(tmpDate, 1);
        }
        return tableSet;
    }

    /*时间模式是单调递增的*/
    private static Date dealTableName(String physicsTableName) {
        String[] s = physicsTableName.split("_");
        Date date = DateExtUtil.strToDate(s[s.length - 1], DateExtUtil.YYYYMM);
        return date;
    }
}



